package com.lovi.myusercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lovi.myusercenter.common.BaseResponse;
import com.lovi.myusercenter.common.ErrorCode;
import com.lovi.myusercenter.common.Result;
import com.lovi.myusercenter.constant.UserConstant;
import com.lovi.myusercenter.domain.User;
import com.lovi.myusercenter.domain.request.UserLoginRequest;
import com.lovi.myusercenter.domain.request.UserRegisterRequest;
import com.lovi.myusercenter.exception.BusinessException;
import com.lovi.myusercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController
@Slf4j
@RequestMapping("/user")
//@CrossOrigin(origins = {"http://47.113.218.42","http://localhost:3000","http://localhost:8000","http://fox-user.lovi.love"},allowedHeaders = "true")//允许跨域,失败了！
public class UserController {
    @Resource
    UserService userService;

    /**
     * 用户注册
     * @param userRegisterRequest 用户注册请求体
     * @return
     */
    @PostMapping(value="/register", consumes= MediaType.APPLICATION_JSON_VALUE)
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){

        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if(StringUtils.isAnyBlank(userAccount , password, checkPassword)){
            log.info("注册体有东西为null");
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Long userId = userService.userRegister(userAccount, password, checkPassword);
        return Result.success(userId);

    }

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return 脱敏后的用户
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        String userAccount = userLoginRequest.getUserAccount();
        String password = userLoginRequest.getPassword();
        if(StringUtils.isAnyBlank(userAccount , password)){
            log.info("登录体有东西为null");
            return Result.fail(ErrorCode.NULL_ERROR);
        }
        User safeUser = userService.userLogin(userAccount, password, request);
        return Result.success(safeUser);
    }
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogin(HttpServletRequest request){
        if(request==null){
            log.info("注销失败，没查到登录态");
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        int i = userService.userLogOut(request);
        return Result.success(i);

    }

    /**
     * 获取当前用户信息
     * @param request
     * @return 脱敏后的用户
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        //查询数据库(获取最新的用户信息)
        user = userService.getById(user.getId());
        //脱敏
        User safeUser = userService.getSafeUser(user);
        return Result.success(safeUser);
    }

    /**
     * 通过账号名查询用户信息(模糊查询，可以查到一组用户信息）
     * @param userName 用户名：账号
     * @param request
     * @return 脱敏后的用户
     */
    @GetMapping("/searchByName/{userName}")
    public BaseResponse<List<User>> searchUserByName(@PathVariable String userName,HttpServletRequest request){
        //先鉴权，(没有权限就返回空数组）
        if(!userService.hasAdminAuthority(request)){
            return Result.success(new ArrayList<User>());

        }
        //数据库模糊查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(userName)){
            queryWrapper.like("user_account",userName);
        }
        List<User> users = userService.list(queryWrapper);
        List<User> safeUserList =  new ArrayList<>();

        //脱敏
        for (User user : users) {
            safeUserList.add(userService.getSafeUser(user));
        }
        return Result.success(safeUserList);
    }

    /**
     * 根据id删除用户
     * @param id 用户id
     * @param request 用户session信息
     * @return 删除成功/失败
     */
    @PostMapping ("/delete/{id}")
    public BaseResponse<Boolean> deleteUserById(@PathVariable Long id,HttpServletRequest request){
        //鉴权
        if(id==0 || userService.hasAdminAuthority(request)==false){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //删除数据库数据
        boolean deleteResult = userService.removeById(id);
        return Result.success(deleteResult);
    }
    @PostMapping ("/delete2")
    public BaseResponse<Boolean> deleteUserById2(@RequestBody Long id,HttpServletRequest request){
        //鉴权
        if(id==0 || userService.hasAdminAuthority(request)==false){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //删除数据库数据
        boolean deleteResult = userService.removeById(id);
        return Result.success(deleteResult);

    }

    @GetMapping("/getAllUsers")
    public BaseResponse<List<User>> getAllUsers(HttpServletRequest request){
        //鉴权
        if(userService.hasAdminAuthority(request)==false){
            log.info("您没有权限");
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //查询
        return Result.success(userService.getAllUsers());

    }



}
